import { Component, forwardRef, ChangeDetectionStrategy, ChangeDetectorRef, OnInit, QueryList, ViewChildren } from '@angular/core';
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import { DropResult } from 'ngx-smooth-dnd';
import { ControlOption } from 'src/app/admin/dashboard/dashboard-model';
import { MdcRadio } from '@angular-mdc/web';
import { find, propEq } from 'ramda';

@Component({
  selector: 'app-options-field',
  templateUrl: './options-field.component.html',
  styleUrls: ['./options-field.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush,
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => OptionsFieldComponent),
    multi: true
  }]
})
export class OptionsFieldComponent implements ControlValueAccessor, OnInit {

  options: ControlOption[] = [];

  radioGroupValue: string;

  constructor(
    public changeDetectorRef: ChangeDetectorRef,
  ) { }

  ngOnInit() {
    this.onTouched();
  }

  writeValue(options: string) {
    this.options = JSON.parse(options);
    this.radioGroupValue = find(propEq('checked', true))(this.options).value;

    this.changeDetectorRef.markForCheck();
  };

  registerOnChange(onChange: any) {
    this.onChange = onChange;
  }

  registerOnTouched(onTouched: any) {
    this.onTouched = onTouched;
  }

  onChange(options: string) { }

  onTouched() { }

  onDrop(dropResult: DropResult) {
    this.options = this.applyDrag(this.options, dropResult);
    this.onChange(JSON.stringify(this.options));
  }

  onInput(event: string, option: ControlOption) {
    option.value = event;
    this.onChange(JSON.stringify(this.options));
  }

  onRadioGroupChange() {
  }

  applyDrag(arr: any, dropResult: DropResult) {
    const { removedIndex, addedIndex, payload } = dropResult;

    if (removedIndex === null && addedIndex === null) {
      return arr;
    };
  
    const result = [...arr];
    let itemToAdd = payload;
  
    if (removedIndex !== null) {
      itemToAdd = result.splice(removedIndex, 1)[0];
    }
  
    if (addedIndex !== null) {
      result.splice(addedIndex, 0, itemToAdd);
    }
  
    return result;
  }
}
